from fastapi import FastAPI, HTTPException
from tortoise.contrib.fastapi import register_tortoise
from contextlib import asynccontextmanager

from app.models import User
from app.schemas import UserCreate, UserResponse
from app.database import init_db, close_db, TORTOISE_ORM

@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_db()  # 初始化数据库
    yield  # 应用运行在此处
    await close_db()  # 关闭数据库连接

app = FastAPI(lifespan=lifespan)

# 注册 Tortoise（提供异常处理）
register_tortoise(
    app,
    config=TORTOISE_ORM,
    add_exception_handlers=True,  # 自动处理 ORM 异常
)

@app.post("/users", response_model=UserResponse)
async def create_user(user: UserCreate):
    db_user = await User.create(**user.model_dump())
    return UserResponse.model_validate(db_user)

@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
    user = await User.get_or_none(id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return UserResponse.model_validate(user)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host='127.0.0.1', port=8000, log_level="info", reload=True)